package org.example.springbootdemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.example.springbootdemo.dao.UserDao;
import org.example.springbootdemo.dto.Result;
import org.example.springbootdemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
public class inddexController {

    //把接口实现自动写完了
    @Autowired
    private UserDao userDao;


    @RequestMapping("/")
    public String index(){
        return "这是首页";
    }


    //登录
    @RequestMapping("/login")
    public Map<String, Object> login(String username, String password){
        Result r=new Result();
        Map<String, Object> map=new HashMap<>();
        QueryWrapper<User> query = Wrappers.query(User.class);
        query.eq("username",username);
        User user =userDao.selectOne(query);

        if (Objects.isNull(user)){
            map.put("code",-1);
            map.put("msg","用户不存在！");
        }else {
            if(Objects.equals(user.getPassword(),password)){
                map.put("code",1);
                map.put("msg","登录成功！");
            }else {
                map.put("code",0);
                map.put("msg","密码错误！");
            }
        }

        return map;
    }

    @PostMapping("/reg")
    public Result reg(String username,String password){
        Result r=new Result();
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        int i =  userDao.insert(user);
        if (i>0){
            r.setCode(1);
            r.setMsg("注册成功");
            r.setData(user);
        }else {
            r.setCode(-1);
            r.setMsg("注册失败");
        }
        return r;
    }
}
